# -*- coding: utf-8 -*-
import scrapy
from homework.items import DangItem


class DangSpider(scrapy.Spider):
    name = 'dang'
    allowed_domains = ['search.dangdang.com']
    start_urls = ['http://search.dangdang.com/?key=python&act=input&page_index=1']

    def parse(self, response):
        blist = response.selector.css('ul.bigimg li')
        for ob in blist:
            item = DangItem()
            item['id'] = ob.css('li::attr(id)').extract_first()
            item['book'] = ob.css('a::attr(title)').extract_first()
            item['title'] = ob.css('p.name a::attr(title)').extract_first()
            if ob.css('a img::attr(data-original)').extract_first() == None:
                item['pic'] = ob.css('a img::attr(src)').extract_first()
            else:
                item['pic'] = ob.css('a img::attr(data-original)').extract_first()
            item['price'] = ob.re_first('<span class="search_now_price">¥([0-9\.]+)</span>')
            item['author'] = ob.css('p.search_book_author span a::attr(title)').extract_first()
            item['time'] = ob.re_first('<span> /(.*?)</span>')
            item['phouse'] = ob.xpath('./p[@class="search_book_author"]//span[3]//a/text()').extract_first()
            item['score'] = ob.re_first('<span style="width: ([0-9]+)\%;"></span>')
            item['detail'] = ob.css('p.detail::text').extract_first()
            yield item

        next_url = response.css('li.next a::attr(href)').extract_first()
        if next_url != None:
            url = response.urljoin(next_url)
            yield scrapy.Request(url=url,callback=self.parse)
